package com.dys.test15;

/**
 * @className: com.dys.test15.ProducerThread
 * @description: 生产者线程
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/08/20 下午8:28
 */
public class ProducerThread extends Thread {

    /**
     * 共享的商品
     */
    private final Product product;

    public ProducerThread(Product product) {
        this.product = product;
    }

    // 生产者生产10个商品
    @Override
    public void run() {
        int counter = 0;
        for (int i = 1; i <= 10; i++) { // i: 生产次数
            // 解决生产者和消费者打印错乱的问题
            synchronized (product) {
                if (i % 2 == 0) {
                    product.setBrand("华为手机");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    product.setName("Mate70Pro");
                    counter++;

                } else {
                    product.setBrand("小米手机");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    product.setName("XiaoMi15Pro");
                    counter++;
                }
                System.out.println("生产者" + counter + "生产了：【" + product.getBrand() + "】---->" + product.getName());
            }
        }
    }
}
